package com.company.management.service.reward.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.management.domain.reward.FileInfo;
import com.company.management.mapper.reward.FileInfoMapper;
import com.company.management.service.reward.SysFileService;
import com.company.management.utils.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;


/**
 * 本地文件存储
 * 
 */
@Service
@Slf4j
public class LocalSysFileServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements SysFileService {
    @Resource
    private FileInfoMapper fileInfoMapper;

    /**
     * 本地文件上传接口
     * 
     * @param file 上传的文件
     * @return 访问地址
     */
    @Override
    public String uploadFile(MultipartFile file) {
        try {
            String uuid = UUID.randomUUID().toString();
            String path = FileUploadUtils.uploadFile(file,uuid);
            FileInfo fileInfo = buildFileInfo(file, path, uuid);
            fileInfoMapper.insert(fileInfo);
            return fileInfo.getFileId();
        } catch (Exception e) {
            log.error("upload file fail",e);
        }
        return null;
    }

    /**
     * @param fileId
     * @Description: 下载文件
     * @Author: wangbin
     * @Date: 2025/3/3 21:24
     */
    @Override
    public void downloadFile(String fileId, HttpServletResponse response) {
        FileInfo fileInfo = fileInfoMapper.selectById(fileId);
        if (Objects.isNull(fileInfo)) {
            log.error("fileInfo not exist");
            return;
        }
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUploadUtils.setAttachmentResponseHeader(response, fileInfo.getFileName());
            FileUploadUtils.writeBytes(fileInfo.getFilePath().concat(File.separator).concat(fileInfo.getFileId()).concat(fileInfo.getFileSuffix()), response.getOutputStream());
        } catch (Exception e) {
            log.error("downlad file error",e);
        }
    }

    private FileInfo buildFileInfo(MultipartFile file, String uploadPath,String uuid) {
        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileId(uuid);
        String originalFilename = file.getOriginalFilename();
        fileInfo.setFileName(originalFilename);
        fileInfo.setFilePath(uploadPath);
        fileInfo.setFileSuffix(originalFilename.substring(originalFilename.lastIndexOf(".")));
        fileInfo.setCreateDateTime(new Date());
        return fileInfo;
    }
}